// 封装axios库
import axios from "axios";

const BASE_URL = "/api"; //这里的baseurl是做了跨域处理
// const BASE_URL = "/api2";
const TIMEOUT = 10000;

class HYReqest {
  constructor(baseURL, timeout = 10000) {
    this.instance = axios.create({
      baseURL,
      timeout,
    });

    // 1.请求拦截
    this.instance.interceptors.request.use(
      (config) => {

        const token = localStorage.getItem("token");
        // console.log("请求拦截器", config);
        if (config.headers && token) {
          //类型缩小
          config.headers.Authorization = "Bearer " + token;
          console.log("请求拦截");
        }
        return config;
      },
      (err) => {
        return err;
      }
    );

    // 2.响应拦截
    this.instance.interceptors.response.use(
      (config) => {

        console.log("响应拦截");
        return config;
      },
      (err) => {

        console.log(err);
        return err;
      }
    );
  }
  request(config) {
    return new Promise((resolve, reject) => {
      this.instance
        .request(config)
        .then((res) => {
        //   console.log(res);
          resolve(res.data);
        })
        .catch((err) => {
          reject(err);

        });
    });
  }
  get(config) {
    return this.request({ ...config, method: "get" });
  }

  post(config) {
    return this.request({ ...config, method: "post" });
  }
}

// y也可以在引入时创建实例
// const hyRequest1 = new HYReqest("http://123.207.32.32:8000")

// 在导出时,直接导出一个实例,这样在用的时候就不用创建实例了
export default new HYReqest(BASE_URL, TIMEOUT);
